package com.oa.android.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.oa.android.R;
import com.oa.android.adapter.SendrecyclerAdapter;
import com.oa.android.utils.MapLocationHelper;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by zouqh on 2018/4/1.
 */

public class SendPictureActivity extends BaseActivity implements View.OnClickListener {


    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;
    @InjectView(R.id.qdTime)
    TextView qdTime;
    @InjectView(R.id.qdAddress)
    TextView qdAddress;
    @InjectView(R.id.content)
    EditText content;
    @InjectView(R.id.textNum)
    TextView textNum;
    @InjectView(R.id.comName)
    TextView comName;

    @InjectView(R.id.recyclerView)
    RecyclerView recyclerView;
    @InjectView(R.id.submit)
    TextView submit;
    private String TAG = SendPictureActivity.class.getName();

    private ArrayList<String> list = new ArrayList<>();
    private SendrecyclerAdapter adapter;
    ProgressDialog dialog;

    private String lng;
    private String addres;
    private boolean flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_picture_activity);
        ButterKnife.inject(this);
        close.setOnClickListener(this);
        getId();
        addres = getIntent().getStringExtra("str");
        qdAddress.setText("" + addres);
        lng = getIntent().getStringExtra("lng");
        comName.setText("" + UConstants.ComName);
        submit.setOnClickListener(this);
        initView();

    }

    private String idStr;

    //获取ID
    public void getId() {
        Util.printLog("------------UConstants.GET_ID-----", UConstants.GET_ID);
        RequestParams params = new RequestParams(UConstants.GET_ID);
//        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "LKQ");


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");
                        String msg = object.getString("msg");
                        if (success) {
                            idStr = msg;

                        } else {
                            Toast.makeText(x.app(), "获取id失败！", Toast.LENGTH_LONG).show();

                        }
//
                    } catch (JSONException e) {

                        Toast.makeText(x.app(), "获取id失败！", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取id失败！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        qdTime.setText(new SimpleDateFormat("HH:mm").format(new Date()));
        if (flag){
                addres = MapLocationHelper.getInstance().getAddress();
                lng = MapLocationHelper.getInstance().getLongitude()+","+MapLocationHelper.getInstance().getLatitude();
        }else{
            flag = true;
        }
    }

    protected void initView() {
        titleText.setText("签到");
//        rightText.setText("发布");
//        rightText.setVisibility(View.VISIBLE);
//        rightText.setOnClickListener(this);
        close.setOnClickListener(this);
//        rightText.setOnClickListener(this);
//        selectAddress.setOnClickListener(this);
        setRecyclerview();
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i(TAG, "输入文字中的状态，count是输入字符数");
                Log.i(TAG, content.getText().toString());
                textNum.setText(content.getText().toString().length() + "/200");
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                Log.i(TAG, "输入文本之前的状态");
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.i(TAG, "输入文字后的状态");
            }
        });
    }

    private Uri mPhotoUri = null;

    private void setRecyclerview() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        recyclerView.setLayoutManager(gridLayoutManager);
        adapter = new SendrecyclerAdapter(list, SendPictureActivity.this);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickLitener(new SendrecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, SendrecyclerAdapter.BaseViewHolder viewHolder) {

                ContentValues contentValues1 = new ContentValues();
                mPhotoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues1);
                startTakePhotoActivity(SendPictureActivity.this, 1001, mPhotoUri);
            }

        });
        adapter.setOnLongItemClickLitener(new SendrecyclerAdapter.OnLongItemClickListener() {
            @Override
            public void OnLongItemClick(int position, SendrecyclerAdapter.BaseViewHolder viewHolder) {
                list.remove(position);
                adapter.notifyDataSetChanged();
            }
        });
    }


    /**
     * 打开相机
     *
     * @param context
     * @param requestCode
     * @param photoUri
     */
    private void startTakePhotoActivity(Activity context, int requestCode, final Uri photoUri) {
        File file = new File(getPhotoPath(context, photoUri, null));
        Uri fileUri = Uri.fromFile(file);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        context.startActivityForResult(intent, requestCode);
    }

    public static String getPhotoPath(Context context, Uri photoUri, Intent data) {
        String photoPath = "";
        ContentResolver cr = context.getContentResolver();
        if (photoUri != null) {
            Cursor cursor = cr.query(photoUri, null, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                int pathIndex = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                photoPath = cursor.getString(pathIndex);
                cursor.close();
            }
        } else {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null && !TextUtils.isEmpty(uri.getPath())) {
                    photoPath = uri.getPath();
                    if (!(new File(photoPath).exists())) {
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor actualimagecursor = cr.query(uri, proj, null,
                                null, null);
                        int actualImg = actualimagecursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        actualimagecursor.moveToFirst();
                        if (actualimagecursor != null)
                            photoPath = actualimagecursor.getString(actualImg);
                    }
                }
            }
        }
        return photoPath;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.submit:
                if (TextUtils.isEmpty(addres)){
                    addres = MapLocationHelper.getInstance().getAddress();
                }

                if (TextUtils.isEmpty(lng)){
                    lng = MapLocationHelper.getInstance().getLongitude()+","+MapLocationHelper.getInstance().getLatitude();
                }

                if (TextUtils.isEmpty(idStr)) {
                    Toast.makeText(x.app(), "获取id失败！", Toast.LENGTH_LONG).show();
                    return;
                }
                dialog = ProgressDialog.show(SendPictureActivity.this, null, "签到中...", true, false);

                if (null!=list&&list.size()>0){
                    upFj();
                }else {
                    updateLocation();
                }
                break;

//                startActivity(GeocodeSearchActivity.class);

        }
    }


    //用户选中图片后，拿到回掉结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK) {
//            listImagePath = data.getStringArrayListExtra(EXTRA_RESULT);
            String photoPath = getPhotoPath(this, mPhotoUri, data);
            Log.e("photoPath---", "" + photoPath);
            list.add(photoPath);
            adapter.notifyDataSetChanged();
        }

        if (requestCode == 11) {

        }
    }

    //压缩 拿到返回选中图片的集合url，然后转换成file文件
//    public void compress(ArrayList<String> list) {
//        for (String imageUrl : list) {
//            Log.e(">>>>>>", imageUrl);
//            File file = new File(imageUrl);
//            compressImage(file);
//        }
////        mList.addAll(list);
//        adapter.addAll(list);
//    }

    //    //压缩
    private void compressImage(File file) {


        Luban.with(SendPictureActivity.this)//用的第三方的压缩，开源库  Luban 大家可以自行百度
                .load(file) //传人要压缩的图片
                .ignoreBy(100)// 忽略不压缩图片大小
//                .setTargetDir(getPath())// 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        //TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(final File file) {
                        URI uri = file.toURI();
                        String[] split = uri.toString().split(":");
                        list.add(split[1]);//压缩后返回的文件，带file字样，所以需要截取
                        Log.e("sendPictureActiviy-----", uri + "????????????" + split[1]);
                    }

                    @Override
                    public void onError(Throwable e) {
                        //TODO 当压缩过去出现问题时调用
                    }
                }).launch();//启动压缩

    }


    //上传附件
    public void upFj() {
        if (TextUtils.isEmpty(idStr)) {
            Toast.makeText(x.app(), "获取id失败！", Toast.LENGTH_LONG).show();
            dialog.dismiss();
            return;
        }
        RequestParams params = new RequestParams(UConstants.UP_FILI);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("TNAME", "LKQ");
        params.addBodyParameter("XH", idStr);
        Util.printLog("UConstants.UP_FILI------------onSuccess-----", UConstants.UP_FILI);
        for (int i = 0; i < list.size(); i++) {
            params.addBodyParameter("FILE", new File(list.get(i)));
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");

//                        String msg = object.getString("msg");
                        if (success) {
                            updateLocation();
                        } else {
                            dialog.dismiss();
                            Toast.makeText(x.app(), "附件上传失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        dialog.dismiss();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "附件上传出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    //上传定位
    public void updateLocation() {

        RequestParams params = new RequestParams(UConstants.QD_URL);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("USERID", UConstants.EmpId);
        params.addBodyParameter("DZ", addres);
        params.addBodyParameter("BZ", content.getText().toString()+"");
        params.addBodyParameter("LNG", lng);
        params.addBodyParameter("ID", idStr);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dialog.dismiss();
                Util.printLog("getDownRoute------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        boolean success = object.getBoolean("success");

//                        String msg = object.getString("msg");
                        if (success) {

                            Toast.makeText(x.app(), "签到成功！", Toast.LENGTH_LONG).show();
                            finish();

                        } else {
                            Toast.makeText(x.app(), "签到失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        dialog.dismiss();
                        Toast.makeText(x.app(), "签到失败！", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "出错！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
